package org.kaede.alimama.client;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
* @author Kaede E-mail:yehan@51xianqu.net
* @version 创建时间：2015年10月16日 下午3:55:25
* 类说明
*/
@ChannelHandler.Sharable
public class AlimamaClientHandler extends SimpleChannelInboundHandler<String> {
	Context context;

	public AlimamaClientHandler(Context context) {
		this.context = context;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext arg0, String url) throws Exception {
		Log.i("Alimama", "result:" + url);
		if(url.equals("nopopularize")) {
			Looper.prepare();
			Toast.makeText(context, "该商品商家没有推广", Toast.LENGTH_LONG).show();
			Looper.loop();
		}
		else if(url.equals("error")) {
			Looper.prepare();
			Toast.makeText(context, "服务暂不可用，请稍后再试", Toast.LENGTH_LONG).show();
			Looper.loop();
		}
		else {
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Uri content_url = Uri.parse(url); // 淘宝商品的地址
			intent.setData(content_url);
			// intent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
			context.startActivity(intent);
		}
		arg0.channel().close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println(cause);
		super.exceptionCaught(ctx, cause);
	}

	private boolean isAppInstalled(Context context,String packagename)
	{
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
		}catch (PackageManager.NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if(packageInfo ==null){
			//System.out.println("没有安装");
			return false;
		}else{
			//System.out.println("已经安装");
			return true;
		}
	}
}
